<template>
  <div class="add-box">
    <div class="permiss-box">
      <span class="title">角色权限预览</span>
      <el-form
        ref="roleForm"
        :model="formData"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="上级角色">
          <el-cascader
            ref="cascaderRef"
            v-model="formData.parentId"
            placeholder="请选择上级角色"
            clearable
            :style="{ width: '100%' }"
            :options="roleOptions"
            :show-all-levels="false"
            popper-class="cascader-theder"
            :props="{
              expandTrigger: 'hover',
              checkStrictly: true,
              emitPath: false,
              value: 'id',
              label: 'roleName'
            }"
            @change="handlerSelectData"
          />
        </el-form-item>
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="formData.roleName" clearable placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="角色编码" prop="roleCode">
          <el-input
            v-model="formData.roleCode"
            :disabled="popConfig.popType === 'edit'"
            clearable
            placeholder="请输入角色编码"
            maxlength="64"
          />
        </el-form-item>
        <el-form-item label="所属机构" prop="deptId">
          <el-cascader
            ref="deptIdRef"
            v-model="formData.deptId"
            clearable
            placeholder="请选择所属机构"
            :style="{ width: '100%' }"
            :options="deptList"
            :show-all-levels="false"
            popper-class="cascader-theder"
            :props="{
              expandTrigger: 'hover',
              checkStrictly: true,
              emitPath: false,
              value: 'id',
              label: 'deptName'
            }"
            @change="handlerSelectData"
          />
        </el-form-item>
        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            clearable
            placeholder="请输入备注信息"
            maxlength="500"
            resize="none"
          />
        </el-form-item>
      </el-form>
    </div>
    <div class="permiss-box">
      <span class="title">功能权限</span>
      <div class="header-box">
        <el-checkbox
          v-model="isSelectAll"
          class="mt-10"
          @change="selectAll('myTree')"
        >全选/全不选</el-checkbox>
        <el-checkbox
          v-model="isExpand"
          @change="expandAll('myTree')"
        >展开/折叠</el-checkbox>
      </div>
      <div class="menu-info">
        <el-tree
          ref="myTree"
          v-loading="loading"
          show-checkbox
          highlight-current
          default-expand-all
          node-key="menuCode"
          :data="treeData"
          :props="menuDefaultProps"
        />
        <!-- :default-checked-keys="menuDefaultChecked" -->
      </div>
    </div>
    <div class="permiss-box data-limit-box">
      <span class="title">数据权限</span>
      <div class="limit-select">
        <span class="title limit-title">权限范围</span>
        <el-select
          v-model="formData.permissionLevel"
          placeholder="请选择数据权限"
          :style="{ width: '70%' }"
        >
          <el-option
            v-for="(item, index) in infoList['PermissionLevelSelected']"
            :key="index"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </div>
      <div v-show="formData.permissionLevel === 'custom'" class="data-info">
        <div class="header-box mb-10">
          <el-checkbox
            v-model="isSelectAll2"
            class="mt-10"
            @change="selectAll2('dataTree', 'deptList')"
          >全选/全不选</el-checkbox>
          <el-checkbox
            v-model="isExpand2"
            @change="expandAll2('dataTree')"
          >展开/折叠</el-checkbox>
          <el-checkbox v-model="isLink">父子联动</el-checkbox>
        </div>
        <el-tree
          ref="dataTree"
          v-loading="loading"
          show-checkbox
          default-expand-all
          :check-strictly="!isLink"
          node-key="id"
          :data="deptList"
          :props="deptDefaultProps"
        />
        <!-- :default-expanded-keys="deptDefaultOpen"
          :default-checked-keys="deptDefaultChecked" -->
      </div>
    </div>
  </div>
</template>

<script>
import { arr2tree } from '@/utils'
import { dictMixin } from '@/mixin/dict'
import { elementMixin } from '@/mixin/element'

export default {
  name: 'AddRole',
  mixins: [dictMixin, elementMixin],
  props: {
    // 弹窗数据
    popData: {
      type: Object,
      default: () => ({})
    },
    // 弹窗配置
    popConfig: {
      type: Object,
      default: () => ({})
    },
    // 弹窗取消
    close: {
      type: Boolean,
      default: false
    },
    // 弹窗确认
    confirm: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      formData: {
        roleName: '',
        roleCode: '',
        parentId: '',
        deptId: '',
        parentRoleName: '',
        remark: '',
        status: false,
        permissionLevel: ''
      },
      // 菜单权限参数
      loading: false,
      menuDefaultProps: {
        children: 'children',
        label: 'menuName'
      },
      menuDefaultChecked: [],
      treeData: [],
      menuDefaultOpen: [],
      dictOptions: [],
      // 数据权限参数
      deptLoading: false,
      isLink: true,
      deptDefaultProps: {
        children: 'children',
        label: 'deptName'
      },
      deptDefaultChecked: [],
      deptList: [],
      deptDefaultOpen: [],
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
          {
            required: true,
            message: '角色名称长度过长',
            max: 24,
            trigger: 'blur'
          }
        ],
        roleCode: [
          { required: true, message: '请输入角色编码', trigger: 'blur' }
        ],
        deptId: [
          { required: true, message: '请选择所属机构', trigger: 'change' }
        ]
      },
      roleOptions: []
    }
  },
  watch: {
    popData: {
      handler(data) {
        if (data) {
          let formFields = []
          if (this.popConfig.popType === 'edit') {
            formFields = [
              'parentId',
              'roleName',
              'roleCode',
              'deptId',
              'remark',
              'status',
              'parentRoleName',
              'permissionLevel'
            ]
          } else {
            formFields = ['parentId', 'parentRoleName']
          }
          for (const key in this.popData) {
            if (
              Object.hasOwnProperty.call(this.popData, key) &&
              formFields.includes(key)
            ) {
              this.$set(this.formData, key, this.popData[key])
            }
          }
        }
        if (this.popConfig.popType === 'edit') {
          this.getAuthData({
            id: this.popData.id
          })
        }
      },
      deep: true,
      immediate: true
    },
    confirm: {
      handler(confirm) {
        this.submit()
      }
    },
    treeData: {
      handler(val) {
        if (val && val.length && this.menuDefaultChecked.length) {
          this.handlerShowMenu()
        }
      },
      deep: true
    },
    menuDefaultChecked: {
      handler(val) {
        if (val && val.length && this.treeData.length) {
          this.handlerShowMenu()
        }
      },
      deep: true
    },
    deptList: {
      handler(val) {
        if (val && val.length && this.deptDefaultChecked.length) {
          this.handlerShowDept()
        }
      },
      deep: true
    },
    deptDefaultChecked: {
      handler(val) {
        if (val && val.length && this.deptList.length) {
          this.handlerShowDept()
        }
      },
      deep: true
    }
  },
  created() {
    this.getCommonSelecteds(
      'PermissionLevelSelected',
      'PermissionLevelSelected'
    )
    this.getRoleList()
    this.queryDeptList()
    this.queryAllMenu()
  },
  methods: {
    handlerShowMenu() {
      this.$refs.myTree.setCheckedKeys([]) // 先清空选中
      this.$nextTick(() => {
        const that = this
        that.menuDefaultChecked.forEach((i, n) => {
          that.$refs.myTree.setChecked(that.menuDefaultChecked[n], true)
        })
      })
    },
    handlerShowDept() {
      this.$refs.dataTree.setCheckedKeys([]) // 先清空选中
      this.$nextTick(() => {
        const that = this
        that.deptDefaultChecked.forEach((i, n) => {
          that.$refs.dataTree.setChecked(that.deptDefaultChecked[n], true)
        })
      })
    },
    /** 查询所有组织架构 */
    async queryDeptList() {
      this.loading = true
      try {
        const res = await this.$api.menuManage.queryDeptList({})
        if (res.code === '1000') {
          this.deptList = arr2tree(res.data, {
            id: 'id',
            parentId: 'parentId',
            childrenKey: 'children'
          })
        }
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    },
    /** 查询所有权限菜单 */
    async queryAllMenu() {
      this.loading = true
      try {
        const res = await this.$api.menuManage.queryAllMenu({})
        if (res.code === '1000') {
          this.treeData = arr2tree(res.data, {
            id: 'id',
            parentId: 'parentId',
            childrenKey: 'children'
          })
        }
      } catch (error) {
        console.log(error)
      }
      this.loading = false
    },
    async getRoleList() {
      try {
        const param = {}
        const res = await this.$api.roleManage.queryList(param)
        if (res.code === '1000') {
          const list =
            arr2tree(res.data.records, {
              id: 'id',
              parentId: 'parentId',
              childrenKey: 'children'
            }) || []
          this.roleOptions = list
        }
      } catch (error) {
        console.log('error')
      }
    },
    handleChange(value) {
      if (value) {
        this.$set(this.formData, 'parentId', value[value.length - 1])
      } else {
        this.$set(this.formData, 'parentId', '')
      }
    },
    async addRole(params) {
      const res = await this.$api.roleManage.roleAdd(params)
      if (res.code === '1000') {
        this.$message.success('添加成功！')
        this.$emit('onFinish', 'add-role')
      } else {
        console.log('添加异常')
      }
    },
    async editRole(params) {
      params.id = this.popData.id
      const res = await this.$api.roleManage.roleUpdate(params)
      if (res.code === '1000') {
        this.$message.success('修改成功！')
        this.$emit('onFinish', 'add-role')
      } else {
        console.log('修改异常')
      }
    },
    /**
     * 提交
     */
    submit() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          // 获取选中的菜单权限列表 全选
          const checkedKeys = this.$refs.myTree.getCheckedKeys() || []
          // 半选
          const halfCheckedKeys = this.$refs.myTree.getHalfCheckedKeys() || []
          const menuCheckKeys = [...checkedKeys, ...halfCheckedKeys].map(
            (e) => {
              return { menuId: e }
            }
          )
          if (!menuCheckKeys.length) {
            this.$message.error('功能权限不能为空')
            return
          }
          if (!this.formData.permissionLevel) {
            this.$message.error('权限范围不能为空')
            return
          }

          // 获取选中的机构权限列表
          let deptCheckKeys = []
          if (this.formData.permissionLevel === 'custom') {
            const deptCheckedKeys = this.$refs.dataTree.getCheckedKeys() || [] // 全选
            // const deptHalfCheckedKeys = // 半选
            //   this.$refs.dataTree.getHalfCheckedKeys() || []
            deptCheckKeys = [...deptCheckedKeys].map((e) => {
              return { deptId: e }
            })
            if (!deptCheckKeys.length) {
              this.$message.error('数据权限不能为空')
              return
            }
          }
          const {
            roleName,
            roleCode,
            parentId,
            deptId,
            permissionLevel,
            remark,
            status
          } = this.formData
          const params = {
            roleName,
            roleCode,
            parentId,
            deptId,
            permissionLevel,
            remark,
            status: status ? 0 : 1,
            menuList: menuCheckKeys,
            roleDeptList: deptCheckKeys
          }
          if (this.popConfig.popType === 'edit') {
            this.editRole(params)
          } else {
            this.addRole(params)
          }
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 处理选择事件
    handlerSelectData() {
      const { cascaderRef } = this.$refs
      if (cascaderRef) {
        cascaderRef.dropDownVisible = false
      }
    },
    // 获取用户权限信息
    async getAuthData(params) {
      this.loading = true
      try {
        const res = await this.$api.roleManage.detail(params)
        if (res.code === '1000') {
          const { ownMenuList = [], ownDeptList = [] } = res.data
          // this.setCheckedKeys(ownMenuList)
          const newOwnMenuList = ownMenuList.map((e) => e.menuId)
          this.$set(this, 'menuDefaultChecked', newOwnMenuList)
          this.$set(
            this,
            'deptDefaultChecked',
            ownDeptList.map((e) => e.deptId) || []
          )
        }
        this.loading = false
      } catch (error) {
        console.log(error)
        this.loading = false
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.add-box {
  color: #333;
  display: flex;
  max-height: 50vh;
  border: 1px solid #e7e7e7;

  .permiss-box {
    display: flex;
    flex-direction: column;
    padding: 14px;
    width: 390px;
    border-right: 1px solid #e7e7e7;

    .title {
      font-size: 14px;
      font-weight: 500;
      color: #303133;
    }
    .el-form {
      margin-top: 16px;
    }
  }
  .menu-info {
    margin-top: 14px;
    flex: 1;
    overflow-y: auto;
  }

  .data-info {
    margin-top: 14px;
    flex: 1;
    overflow-y: auto;
  }

  .limit-select {
    margin-top: 14px;
  }

  .limit-title {
    margin-right: 14px;
  }
}
</style>
